import { computed } from 'vue';

interface UseVModelOptions {
  props: any;
  propsName: string;
  emit: (event: string, value: any) => void;
}
export function useVModel({ props, propsName, emit }: UseVModelOptions): ComputedRef<any> {
  const model: any = computed({
    get() {
      const proxy = new Proxy(props[propsName], {
        get(target: any, key: string) {
          return Reflect.get(target, key);
        },
        set(target: any, key: string, value: any) {
          emit('update:' + propsName, {
            ...target,
            [key]: value,
          });
          return true;
        },
      });
      return proxy;
    },
    set(val) {
      emit('update:' + propsName, val);
    },
  });
  return model;
}
